//
//  ConnectDeviceVC.swift
//  NewXueBa
//
//  Created by Shine on 2019/6/18.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import UIKit
/*
    没有蓝牙的时候 Gloab_Connect_Device全局保存的清除未 nil
    断开 SDK的设备连接
    被连接的设备无法被搜索到
    刚进入的时候就搜索，比对如果存在的全局，进行初始化数据
    点击设备进行数据的修改
 */

//设备mode
class BCDeviceModel {
    var device = RobotPenDevice()
    var connectState: String = "未连接"
}

class ConnectDeviceVC: BCBaseVC {

    @IBOutlet weak var deviceTab: UITableView!
    @IBOutlet weak var remindView: UIView!
    @IBOutlet weak var remindImageV: UIImageView!
    @IBOutlet weak var remindTitle: UILabel!
    @IBOutlet weak var searchBtn: BCUIButton!
    @IBOutlet weak var seekImageV: UIImageView!
    
    var deviceArray = [BCDeviceModel]()
    fileprivate var timer: Timer?
    fileprivate var count: Int = 10
    var selectIndex: IndexPath? //点击选择的单元格的位置
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUIData()
        seekImageV.seekLoadingAnimation()
        //遵守RobotPenManager协议，必须实现
        RobotPenManager.share()?.setPenDelegate(self)
        // 搜索设备
        searchBtnClick(searchBtn)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        timer?.invalidate()
        timer = nil
    }
    
    @IBAction func backClick(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func searchBtnClick(_ sender: BCUIButton) {
        /* 搜索中的状态 */
        remindImageV.image = UIImage(named: "bluetooth_bg")
        remindTitle.text = "请将设备贴近手机"
        searchBtn.setTitle("设备搜索中", for: .normal)
        searchBtn.setTitleColor(UIColor.hex(hexString: "#7F899A"), for: .normal)
        searchBtn.isUserInteractionEnabled = false
        seekImageV.isHidden = false
        //数据重置
        deviceArray.removeAll()
        if let conDevice = Gloab_Connect_Device,
            conDevice.peripheral.state == .connected { //当保存有，且设备的蓝牙状态为连接
            let mode = BCDeviceModel()
            mode.connectState = "已连接"
            deviceArray.append(mode)
        }
        // 搜索设备
        RobotPenManager.share()?.scanDevice(withALL: false)
        count = 10
        selectIndex = nil
        sendTime()
    }
}

extension ConnectDeviceVC {
    
    fileprivate func setUIData() {
        self.fd_prefersNavigationBarHidden = true //隐藏导航栏
        remindView.isHidden = false
        deviceTab.tableFooterView = UIView()
    }
    
    fileprivate func sendTime()  {
        if timer == nil {
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.countdown), userInfo: nil, repeats: true)
        }
        CFRunLoopAddTimer(CFRunLoopGetMain(), self.timer, CFRunLoopMode.defaultMode)
        
    }
    // 定时器执行的变化事件
    @objc fileprivate func countdown() {
        count -= 1
        if count == 0 {
            if deviceArray.count == 0 {
                remindImageV.image = UIImage(named: "image_no_class")
                remindTitle.text = "未搜索到设备"
            }
            searchBtn.setTitle("重新搜索", for: .normal)
            searchBtn.setTitleColor(UIColor.hex(hexString: "#2E3D4B"), for: .normal)
            searchBtn.isUserInteractionEnabled = true
            seekImageV.isHidden = true
            RobotPenManager.share()?.stopScanDevice() //停止搜索
            deviceTab.reloadData()
        }
    }
}

//pragma mark- ========== SDK 协议内容 ===========
extension ConnectDeviceVC: RobotPenDelegate {
    //获取点的信息
    func getPointInfo(_ point: RobotPenPoint!) {
        print(point.originalX)
    }
    /**
     发现设备
     @param device device
     */
    func getBufferDevice(_ device: RobotPenDevice!) {
        print(device.deviceName ?? "发现新设备")
        let model = BCDeviceModel()
        model.device = device
        deviceArray.append(model)
        deviceTab.reloadData()
    }
    /**
     获取设备状态 （设备连接状态 ）
     @param State state
     */
    func getDeviceState(_ State: DeviceState, deviceUUID uuid: String!) {
        
        guard let index = selectIndex else {
           return
        }
        
        let mode = deviceArray[index.row]
        let cell = deviceTab.cellForRow(at: index) as! DeviceListCell
        
        switch State {
        case DEVICE_DISCONNECTED:
            print("断开连接") //蓝牙连接断开
            mode.connectState = "未连接"
            Gloab_Connect_Device = nil
            BCUserManager.shareManager.BlueTooth_isOpen.value = BCUserManager.shareManager.BlueTooth_isOpen.value //激发观察
        case DEVICE_CONNECT_FAIL:
            print("连接失败")
            cell.seekLaodImageV.isHidden = true
            cell.connectState.isHidden = false
            mode.connectState = "连接失败"
        case DEVICE_CONNECTE_SUCCESS:
            mode.connectState = "已连接"
            cell.seekLaodImageV.isHidden = true
            cell.connectState.isHidden = false
            RobotPenManager.share()?.stopScanDevice() //停止搜索
        case DEVICE_INFO_END:
            //获取设备信息完成，大部分设备信息会在这里获取完毕。建议设备信息在这里获取、赋值。
            let device = RobotPenManager.share()?.getConnectDevice()
            Gloab_Connect_Device = device
            BCUserManager.shareManager.BlueTooth_isOpen.value = BCUserManager.shareManager.BlueTooth_isOpen.value //激发观察
        default:
            break
        }
        cell.cellModel = mode // 从新赋值
    }
    
}

extension ConnectDeviceVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        remindView.isHidden = deviceArray.count > 0 ? true : false
        return deviceArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceListCell") as! DeviceListCell
        cell.cellModel = deviceArray[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let cell = deviceTab.cellForRow(at: indexPath) as! DeviceListCell
        selectIndex = indexPath
        let model = deviceArray[indexPath.row]
        if model.connectState == "未连接" {
            cell.seekLaodImageV.isHidden = false
            cell.connectState.isHidden = true
            cell.seekLaodImageV.seekLoadingAnimation()
            RobotPenManager.share()?.connect(model.device)
        } else if model.connectState == "已连接" {
            let alert = UIAlertController.init(title: nil, message: "确认断开连接吗?", preferredStyle: .alert)
            let actionCancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
            let actionEnter = UIAlertAction.init(title: "确定", style: .default) { (action) in
                Gloab_Connect_Device = nil
                RobotPenManager.share()?.disconnectDevice()//断开设备
                self.selectIndex = nil
                model.connectState = "未连接"
            }
            alert.addAction(actionCancel)
            alert.addAction(actionEnter)
            self.present(alert, animated: true, completion: nil)
        }
        
    }
}
